<template>
  <div class="order-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">订单管理</span>
          <!-- 可能添加其他操作按钮 -->
        </div>
      </template>

      <!-- 搜索和过滤区域 -->
      <div class="search-area">
        <el-row :gutter="20">
           <el-col :span="6">
            <el-input
              v-model="searchBoardName"
              placeholder="请输入餐桌名称搜索"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select v-model="filterStatus" placeholder="订单状态" clearable>
              <el-option
                v-for="status in orderStatusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              ></el-option>
            </el-select>
          </el-col>
           <el-col :span="6">
            <el-select v-model="filterType" placeholder="订单类型" clearable>
              <el-option
                v-for="type in orderTypeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="6" style="text-align: right;">
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 表格区域 -->
      <div class="table-container">
        <table class="order-table">
          <thead>
            <tr>
              <th>订单编号</th>
              <th>餐桌名称</th>
              <th>总金额</th>
              <th>实付金额</th>
              <th>订单类型</th>
              <th>状态</th>
              <th>下单时间</th>
              <th>操作人</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in filteredOrders" :key="item.orderId">
              <td>{{ item.orderId }}</td>
              <td>{{ item.boardName }}</td>
              <td>{{ item.totalAmount.toFixed(2) }}</td>
              <td>{{ item.payableAmount.toFixed(2) }}</td>
              <td>
                <el-tag :type="item.orderType === 1 ? 'success' : 'info'">
                  {{ getOrderTypeText(item.orderType) }}
                </el-tag>
              </td>
              <td>
                <el-tag :type="getOrderStatusType(item.orderStatus)">
                  {{ getOrderStatusText(item.orderStatus) }}
                </el-tag>
              </td>
              <td>{{ item.placeOrderTime }}</td>
              <td>{{ item.operatorName }}</td>
              <td class="actions-column">
                <div class="action-buttons">
                  <el-button
                    size="small"
                    type="primary"
                    @click="handleViewDetails(item)"
                  >
                    查看详情
                  </el-button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <!-- <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalOrders"
        style="margin-top: 20px; text-align: right;"-->
      <!-- ></el-pagination> -->
    </el-card>

    <!-- 订单详情对话框 -->
     <el-dialog
      v-model="detailsDialogVisible"
      :title="'订单详情'"
      width="60%"
    >
      <!-- 订单详情内容 -->
      <div v-if="currentOrderDetails">
        <p><strong>订单编号:</strong> {{ currentOrderDetails.orderId }}</p>
        <p><strong>餐桌名称:</strong> {{ currentOrderDetails.boardName }}</p>
        <p><strong>总金额:</strong> {{ currentOrderDetails.totalAmount.toFixed(2) }}</p>
        <p><strong>优惠金额:</strong> {{ currentOrderDetails.discountAmount.toFixed(2) }}</p>
        <p><strong>实付金额:</strong> {{ currentOrderDetails.payableAmount.toFixed(2) }}</p>
        <p><strong>订单类型:</strong> {{ getOrderTypeText(currentOrderDetails.orderType) }}</p>
        <p><strong>订单状态:</strong> {{ getOrderStatusText(currentOrderDetails.orderStatus) }}</p>
        <p><strong>下单时间:</strong> {{ formatTimestamp(currentOrderDetails.placeOrderTime) }}</p>
        <p><strong>支付时间:</strong> {{ formatTimestamp(currentOrderDetails.paymentTime) }}</p>
        <p><strong>操作人:</strong> {{ currentOrderDetails.operatorName }}</p>
         <p v-if="currentOrderDetails.orderType === 2"><strong>配送地址:</strong> {{ currentOrderDetails.shippingAddress }}</p>
        <p><strong>备注:</strong> {{ currentOrderDetails.remark }}</p>

        <h4>订单菜品:</h4>
        <el-table :data="currentOrderDetails.items" style="width: 100%">
          <el-table-column prop="dish.dishName" label="菜品名称" />
          <el-table-column prop="orderItem.quantity" label="数量" width="80" />
          <el-table-column prop="dish.price" label="单价" width="100" />
          <el-table-column label="总价" width="100">
            <template #default="scope">
              {{ (scope.row.dish.price * scope.row.orderItem.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { orderApi } from '../api/console'

// 接口类型定义
interface Order {
  orderId: number
  boardId: number // 可用于关联餐桌信息
  boardName?: string // 假设后端会返回餐桌名
  totalAmount: number
  discountAmount: number
  payableAmount: number
  orderType: number // 1 = 堂食，2 = 外卖
  orderStatus: string // 使用字符串类型，例如 "PAID"
  placeOrderTime: number // 修改为 number 类型 (时间戳)
  paymentTime: number | null // 修改为 number | null 类型 (时间戳)
  remark: string
  shippingAddress: string // 假设是格式化好的字符串
  uid: number // 操作人ID
  // uName?: string // 假设后端会返回操作人姓名
  operatorName?: string // 后端返回的操作人名称
  items?: OrderItem[] // 订单项列表
}

interface OrderItem {
   orderItem: {
    itemId: number
    orderId: number
    dishId: number
    quantity: number
  }
  dish: {
    dishId: number
    dishName: string
    price: number
    // 其他菜品信息如果需要也可以加上
  }
}

// 状态定义
const loading = ref(false)
const orders = ref<Order[]>([])
const searchBoardName = ref<string>('')
const filterStatus = ref<string>('') // 修改为字符串类型
const filterType = ref<number | ''>('')

const detailsDialogVisible = ref(false)
const currentOrderDetails = ref<Order | null>(null)

// 订单状态选项 (根据数据库定义，但值使用后端返回的字符串枚举)
const orderStatusOptions = [
  { value: 'PAID', label: '已支付' },
  { value: 'TO_BE_PAID', label: '待支付' },
  { value: 'CANCELED', label: '已取消' }
]

// 订单类型选项 (根据数据库定义)
const orderTypeOptions = [
  { value: 1, label: '堂食' },
  { value: 2, label: '外卖' }
]

// 计算属性：过滤后的订单列表
const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    const boardNameMatch = !searchBoardName.value || (order.boardName && order.boardName.toLowerCase().includes(searchBoardName.value.toLowerCase())) // 使用 camelCase
    const statusMatch = !filterStatus.value || order.orderStatus === filterStatus.value // 使用 camelCase 和字符串比较
    const typeMatch = filterType.value === '' || order.orderType === filterType.value // 使用 camelCase
    return boardNameMatch && statusMatch && typeMatch
  })
})

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true
    const result = await orderApi.getRegionOrders([9, 10])
    if (result.code === 200 && result.data) {
      orders.value = result.data
    } else {
      ElMessage.error(result.message || '获取订单列表失败')
    }
  } catch (error) {
    ElMessage.error('获取订单列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取订单状态标签类型
const getOrderStatusType = (status: string): string => {
  const types: Record<string, string> = {
    'PAID': 'success', // 已支付
    'TO_BE_PAID': 'warning', // 待支付
    'CANCELED': 'danger'   // 已取消
  }
  return types[status] || 'info'
}

// 获取订单状态标签文本
const getOrderStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    'PAID': '已支付',
    'TO_BE_PAID': '待支付',
    'CANCELED': '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取订单类型文本
const getOrderTypeText = (type: number): string => {
    const typeMap: Record<number, string> = {
        1: '堂食',
        2: '外卖'
    }
    return typeMap[type] || '未知类型'
}

// 格式化时间戳为年月日时分秒
const formatTimestamp = (timestamp: number | string | null): string => {
  if (!timestamp) return '-';

  // 尝试将可能是字符串的时间戳转换为数字
  const time = typeof timestamp === 'string' ? parseInt(timestamp, 10) : timestamp;
  if (isNaN(time)) return '-'; // 如果转换后不是有效数字，返回'-'

  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 重置搜索条件
const resetSearch = () => {
  searchBoardName.value = ''
  filterStatus.value = ''
  filterType.value = ''
}

// 处理查看详情
const handleViewDetails = async (order: Order) => {
  currentOrderDetails.value = null // 先清空，避免显示旧数据
  detailsDialogVisible.value = true
  loading.value = true

  try {
    const result = await orderApi.getOrderItems(order.orderId)
    if (result.code === 200 && result.data) {
      currentOrderDetails.value = { ...order, items: result.data } // 合并订单项到订单详情
    } else {
      ElMessage.error(result.message || '获取订单详情失败')
      currentOrderDetails.value = order // 如果获取详情失败，至少显示订单主信息
    }
  } catch (error) {
    ElMessage.error('获取订单详情失败')
    console.error(error)
    currentOrderDetails.value = order // 发生错误时也尝试显示订单主信息
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await fetchOrders()
})

</script>

<style scoped>
.order-list-container {
  margin-left: 200px;
  margin-top: 45px;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.search-area {
  margin-bottom: 20px;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.order-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  min-width: 1000px;
}

.order-table th,
.order-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: center;
  color: #333;
  vertical-align: middle;
}

.order-table th {
  background-color: #f2f2f2;
  font-weight: bold;
  color: #333;
}

.order-table tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

.order-table tbody tr:hover {
  background-color: #f5f5f5;
}

.actions-column {
  white-space: nowrap;
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 120px;
  height: 60px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  width: 100%;
}

.action-buttons .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 0;
}

:deep(.el-select) {
  width: 100%;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .order-list-container {
    margin-left: 0;
    width: 100%;
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    gap: 16px;
  }

  .title {
    width: 100%;
    text-align: center;
  }

  .search-area {
    .el-row {
      margin: 0 !important;
    }
    
    .el-col {
      padding: 0 !important;
      margin-bottom: 10px;
    }
  }

  .el-button {
    width: 100%;
    justify-content: center;
  }
}
</style> 